package models;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.TreeSet;

import javax.persistence.CascadeType;
import javax.persistence.Entity;
import javax.persistence.Lob;
import javax.persistence.ManyToMany;
import javax.persistence.OneToMany;

import play.data.validation.MaxSize;
import play.data.validation.Required;
import play.db.jpa.Model;

@Entity(name = "post")
@SuppressWarnings("deprecation")
public class Post extends Model {

	private static final long serialVersionUID = 1L;

	@Required
	public String title;
	public Date addTime;
	@Lob
	@Required
    @MaxSize(10000)
	public String content;
	public Boolean status;

	@OneToMany(mappedBy = "post", cascade = CascadeType.ALL)
	public List<Comment> comments;
	@ManyToMany(cascade = CascadeType.PERSIST)
	public Set<Tag> tags;

	public Post(String title, String content, Boolean status) {
		this.comments = new ArrayList<Comment>();
		this.tags = new TreeSet<Tag>();
		this.title = title;
		this.content = content;
		this.status = status;
		this.addTime = new Date();
	}

	public Post addComment(String author, String url, String content) {
		Comment newComment = new Comment(this, author, url, content).save();
		comments.add(newComment);
		return this;
	}

	public Post previous() {
		return Post.find("id < ? order by id desc", id).first();
	}

	public Post next() {
		return Post.find("id > ? order by id asc", id).first();
	}

	public Post tagItWith(String name) {
		tags.add(Tag.findOrCreateByName(name));
		return this;
	}

	public static List<Post> findTaggedWith(String tag) {
		System.out.println("come");
        return Post.find(
            "select distinct p from post p join p.tags as t where t.name = ?",
            tag
        ).fetch();
    }
	
	public static List<Post> findTaggedWith(String... tags) {
		return Post.find(
			"select distinct p.id from post p join p.tags as t where t.name in (:tags) group by p.id having count(t.id) = :size")
		.bind("tags", tags).bind("size", tags.length).fetch();
	}

	public String toString() {
		return title;
	}
}
